/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: AuthenticateActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.sdk.account.bean.MobileCodeListBean;
import io.bhex.app.account.presenter.AuthenticatePresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.baselib.constant.Fields;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnDismissListener;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.account.bean.MobileCodeListBean;
import io.bhex.sdk.config.bean.ConfigBean;

/**
 * ================================================
 * 描   述：身份认证
 * ================================================
 */

public class AuthenticateActivity extends BaseActivity<AuthenticatePresenter, AuthenticatePresenter.AuthenticateUI> implements AuthenticatePresenter.AuthenticateUI, View.OnClickListener {
    private static final int REQUEST_CODE_SELECT_IMAGE = 0x013;
    private TextView countryName;
    private TextView idTypeTx;
    private EditText firstnameEt;
    private EditText lastnameEt;
    private EditText idEt;
    private String country = "";
    private int idType = -1;
    //china只使用身份证件
    private String chinaType = "";
    private AlertView kycTypeAction;
    private List<ConfigBean.KycCardTypeBean> mKycTypeList;
    private ConfigBean.KycCardTypeBean mSelectKycType;
    private String[] kycTypeArray;
    private boolean isSelectChina = false;
    private EditText authNameEt;

    @Override
    protected int getContentView() {
        return R.layout.activity_authenticate_layout;
    }

    @Override
    protected AuthenticatePresenter createPresenter() {
        return new AuthenticatePresenter();
    }

    @Override
    protected AuthenticatePresenter.AuthenticateUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        Toolbar toolbar= findViewById(R.id.toolbar);
        CollapsingToolbarLayout collapsingToolbarLayout= findViewById(R.id.collapsing_toolbar);
        // 硬编码黑白版Toolbar标题栏title字色
        collapsingToolbarLayout.setCollapsedTitleTextColor(SkinColorUtil.getDark(this));
        collapsingToolbarLayout.setExpandedTitleColor(SkinColorUtil.getDark(this));

        //显示返回按钮
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        countryName = viewFinder.textView(R.id.auth_country);
        idTypeTx = viewFinder.textView(R.id.auth_id_type);
        authNameEt = viewFinder.editText(R.id.auth_name);
        firstnameEt = viewFinder.editText(R.id.auth_et_firstname);
        lastnameEt = viewFinder.editText(R.id.auth_et_lastname);
        idEt = viewFinder.editText(R.id.auth_et_id);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                KeyBoardUtil.closeKeybord(viewFinder.editText(R.id.auth_et_id), this);
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.auth_country_rela).setOnClickListener(this);
        viewFinder.find(R.id.auth_id_rela).setOnClickListener(this);
        viewFinder.find(R.id.btn_nextstep).setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //获取图片路径
        if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            // 本来就用到 QRCodeView 时可直接调 QRCodeView 的方法，走通用的回调
            getPresenter().uploadImg(imagePath);
            c.close();
        } else if (requestCode == Fields.REQUEST_CODE_AUTH && resultCode == Activity.RESULT_OK && data != null) {
            MobileCodeListBean.MobileCodeBean mobileCodeBean = (MobileCodeListBean.MobileCodeBean) data.getSerializableExtra(Fields.INTENT_MOBILE_CODE);
            if (mobileCodeBean != null) {
                if (mobileCodeBean.getNationalCode().equals("86")) {
                    idTypeTx.setText(chinaType);
                    idType = 1;
                    isSelectChina = true;
                } else {
                    if (isSelectChina) {
                        country = "";
                        idType = -1;
                        idTypeTx.setText(getString(R.string.string_select_please));
                    }
                    isSelectChina = false;
                }
                updateKycCountryShowView(isSelectChina);
                country = mobileCodeBean.getShortName();
                String cName = mobileCodeBean.getCountryName();
                if (!TextUtils.isEmpty(cName)) {
                    countryName.setText(cName);
                }
            }
        } else if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            finish();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.auth_country_rela:
                IntentUtils.goMobileCodeList(this, Fields.REQUEST_CODE_AUTH,Fields.FIELD_COUNTRY_PARAM_TYPE_NATIONALITY);
                break;
            case R.id.auth_id_rela:
                if (TextUtils.isEmpty(country)) {
                    ToastUtils.showLong(this, getString(R.string.string_tips_select_country));
                    return;
                }
                showKycTypeSheet();
                break;
            case R.id.btn_nextstep:
                if (TextUtils.isEmpty(country)) {
                    ToastUtils.showLong(this, getString(R.string.string_tips_select_country));
                    return;
                }
                String name = authNameEt.getText().toString().trim();
                String firstName = firstnameEt.getText().toString().trim();
                String lastName = lastnameEt.getText().toString().trim();
                if (isSelectChina) {
                    if (TextUtils.isEmpty(name)) {
                        ToastUtils.showLong(this, getString(R.string.string_input_name));
                        return;
                    }
                }else{

                    if (TextUtils.isEmpty(firstName)) {
                        ToastUtils.showLong(this, getString(R.string.string_input_firstname));
                        return;
                    }

                    if (TextUtils.isEmpty(lastName)) {
                        ToastUtils.showLong(this, getString(R.string.string_input_lastname));
                        return;
                    }

                    if (idType==-1) {
                        ToastUtils.showLong(this, getString(R.string.string_tips_select_id_type));
                        return;
                    }
                }

                String id = idEt.getText().toString().trim();
                if (TextUtils.isEmpty(id)) {
                    ToastUtils.showLong(this, getString(R.string.string_input_valid_document));
                    return;
                }
                getPresenter().requestBasicVerify(country,name,firstName,lastName,idType,id);
                break;
        }
    }

    @Override
    public void showKycType(List<ConfigBean.KycCardTypeBean> kycCardTypeList) {
        if (kycCardTypeList != null) {
            mKycTypeList = kycCardTypeList;
            kycTypeArray = new String[kycCardTypeList.size()];
            for (int i = 0; i < kycCardTypeList.size(); i++) {
                ConfigBean.KycCardTypeBean kycCardTypeBean = kycCardTypeList.get(i);
                if (kycCardTypeBean.getKey() == 1) {
                    chinaType = kycCardTypeBean.getValue();
                }
                kycTypeArray[i] = kycCardTypeBean.getValue();
            }
        }
    }


    /**
     * 显示Kyctype
     */
    private void showKycTypeSheet() {
        KeyBoardUtil.closeKeybord(idEt, this);
        if (kycTypeArray != null) {
            kycTypeAction = new AlertView(null, null, getString(R.string.string_cancel), null, isSelectChina ? new String[]{chinaType} : kycTypeArray, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    if (position == -1) {
                        return;
                    }
                    if (mKycTypeList != null) {
                        mSelectKycType = mKycTypeList.get(position);
                        idTypeTx.setText(mSelectKycType.getValue());
                        idType = mSelectKycType.getKey();
                    }
                }
            });
            kycTypeAction.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                }
            });
            kycTypeAction.show();
        }
    }

    private void updateKycCountryShowView(boolean isSelectChina) {
        viewFinder.textView(R.id.auth_id).setText(getString(isSelectChina ? R.string.string_id_card_no:R.string.string_valid_document));
        viewFinder.find(R.id.nameLinear).setVisibility(isSelectChina ? View.VISIBLE : View.GONE);
        viewFinder.find(R.id.name2Linear).setVisibility(!isSelectChina ? View.VISIBLE : View.GONE);
    }

}
